import React, { useRef, useState, useEffect, memo } from 'react';
import { View, Text, Animated, PermissionsAndroid, Platform, Image, Easing, ActivityIndicator, Pressable, Dimensions, StyleSheet, TouchableWithoutFeedback } from 'react-native';
import { pTx } from "../../utils/dimensions"
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import LinearGradient from 'react-native-linear-gradient';
import IconFont from '@pingtou/rn-vant-icons'
import httpApi from '../../api';
import RNFetchBlob from "rn-fetch-blob";
import DeviceInfo from 'react-native-device-info';
import { ProgressBar } from '@react-native-community/progress-bar-android';
const NewVersion = memo(({ newVersionRefs }) => {
    const [loading, setLoading] = useState()
    const [open, setOpen] = useState(false)
    const [version, setVersion] = useState(false)
    const animated = useRef(new Animated.Value(0))
    const appVersion = DeviceInfo.getVersion();


    const handleAni = () => {
        Animated.timing(animated.current, {
            toValue: open ? 0 : 1,
            duration: 250,
            useNativeDriver: true,
            easing: Easing.linear
        }).start(() => setOpen(open ? false : true));
    };
    if (newVersionRefs) {
        newVersionRefs.current = handleAni
    }


    const opct = animated.current.interpolate({
        inputRange: [0, 1],
        outputRange: [0, 1]
    });

    const initWritePermission = async () => {
        if (Platform.OS == "android") {
            //id 安卓 1ios
            httpApi.getAppVersion({ id: 0 }).then(res => {
                if (res.data.AppVersion) {
                    if (compareVersion(res.data.AppVersion.Version, appVersion) > 0) {
                        handleAni()
                    }
                    setVersion(res.data.AppVersion)
                }

            })
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
            );
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {

            } else {
            }
        } else {
        }
    }

    useEffect(() => {
        initWritePermission()
    }, [])
    const compareVersion = (v1, v2) => {
        if (v1 == v2) {
            return 0;
        }
        const vs1 = v1.split(".").map(a => parseInt(a));
        const vs2 = v2.split(".").map(a => parseInt(a));

        const length = Math.min(vs1.length, vs2.length);
        for (let i = 0; i < length; i++) {
            if (vs1[i] > vs2[i]) {
                return 1;
            } else if (vs1[i] < vs2[i]) {
                return -1;
            }
        }

        if (length == vs1.length) {
            return -1;
        } else {
            return 1;
        }
    }

    const sendDownload = () => {
        setLoading(true)
        const android = RNFetchBlob.android;
        const downloadDest = `${RNFetchBlob.fs.dirs.DownloadDir}/Tweet${version.Version}.apk`;
        RNFetchBlob.config({
            addAndroidDownloads: {
                useDownloadManager: true,
                title: `${version.Version}.apk`,
                description: "An APK that will be installed",
                mime: "application/vnd.android.package-archive",
                path: downloadDest,
                mediaScannable: true,
                notification: true
            }
        })
            .fetch("GET", version.DownloadURL)
            // .uploadProgress((written, total) => {
            //     console.log('uploaded', written / total)
            // })
            // // listen to download progress event
            // .progress((received, total) => {
            //     console.log('progress', received / total)
            // })
            .then(res => {
                android.actionViewIntent(
                    res.path(),
                    "application/vnd.android.package-archive"
                );
                setLoading(false)
            });
    }

    return open && <Animated.View style={{
        position: 'absolute',
        width: Dimensions.get('screen').width,
        height: Dimensions.get('screen').height,
        backgroundColor: 'rgba(10,12,20,0.6)',
        opacity: opct,
        zIndex: 10
    }}>
        <View style={styles.centeredView}>
            <View style={styles.module}>
                <LinearGradient
                    style={styles.gradientContainer}
                    colors={['rgba(58, 192, 48, 0.1)', 'rgba(58, 192, 48, 0)']}
                    start={{ x: 0, y: 0 }}
                    end={{ x: 0, y: 1 }}
                >
                    <Text style={styles.title}>发现新版本</Text>
                    <Pressable
                        onPress={() => handleAni()}
                        style={styles.cross}
                    >
                        <IconFont name="cross" color={"rgba(10, 12, 20, 1)"} size={pTx(16)} />
                    </Pressable>
                    <Image style={[styles.icon]} source={require('../../assets/image/sj.png')}></Image>
                    <Text style={styles.version}>V {version.Version}</Text>
                    <Text style={styles.versionBorder}></Text>
                    <View style={styles.versionInfo}>
                        {version.UpdateLog?.split(' ').map((item, index) => {
                            return <Text style={styles.versionstyles} key={index}>{item}</Text>
                        })}
                    </View>
                    {/* <ProgressBar
                        styleAttr="Horizontal"
                        indeterminate={false}
                        progress={0.5}
                        style={styles.styleAttr}
                        color="rgba(51, 225, 144, 1)"
                    /> */}
                    <Pressable
                        style={styles.button}
                        onPress={sendDownload}
                        height={1000}
                    >
                        <Text style={styles.buttonStyles}>
                            {loading ? <ActivityIndicator color={'#fff'} /> : '立即更新'}
                        </Text>
                    </Pressable>
                    <Text style={styles.buttonStyles2}>官网下载</Text>
                </LinearGradient>
            </View>
        </View>
    </Animated.View>
})
export default NewVersion

const styles = StyleSheet.create({
    centeredView: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: "center",
        alignItems: "center",
    },
    module: {
        position: "relative",
        width: pTx(303),
        minHeight: pTx(403),
        backgroundColor: "#fff",
        borderRadius: pTx(16),
    },
    gradientContainer: {
        paddingHorizontal: pTx(26),
        paddingVertical: pTx(35),
    },
    icon: {
        position: "absolute",
        top: pTx(-50),
        right: pTx(20),
        width: pTx(153),
        height: pTx(156),
    },
    title: {
        fontSize: pTx(25),
        color: "rgba(10, 12, 20, 1)",
        fontWeight: "bold"
    },
    cross: {
        position: "absolute",
        top: pTx(20),
        right: pTx(20),
        zIndex: 1
    },
    version: {
        marginTop: pTx(12),
        fontSize: pTx(16),
        color: "rgba(58, 192, 48, 1)",
        fontWeight: "bold",
    },
    versionInfo: {
        marginTop: pTx(12),
        minHeight: pTx(140),
    },
    versionstyles: {
        fontSize: pTx(16),
        lineHeight: pTx(32),
        color: "rgba(10, 12, 20, 1)",
    },
    versionBorder: {
        marginTop: pTx(12),
        height: pTx(5),
        width: pTx(50),
        backgroundColor: "rgba(31, 31, 31, 1)",
        borderTopRightRadius: pTx(3),
    },
    button: {
        marginTop: pTx(12),
        justifyContent: "center",
        alignItems: "center",
        height: pTx(45),
        backgroundColor: "rgba(58, 192, 48, 1)",
        borderRadius: pTx(4),
    },
    buttonStyles: {
        color: "rgba(255, 255, 255, 1)",
    },
    buttonStyles2: {
        marginTop: pTx(20),
        textAlign: "center"
    },
    styleAttr: {
        height: 3,
    }
})